package com.hmeter.hadoop.common;

import java.io.IOException;
import java.io.InputStream;
import com.jcraft.jsch.*;

public class SSHConnector {
	
	private String hostName = "";
	private int port = 22;
	private String userName = "";
	private String password = "";
	private InputStream is;
	
	JSch jsch = new JSch();
	
	public SSHConnector(String hostName, int port, String userName, String password)
	{
		this.hostName = hostName;
		this.port = port;
		this.userName = userName;
		this.password = password;
	}
	
	public Session openSSHConnection() throws JSchException
	{
		Session session = null;
		try 
		{
			session = jsch.getSession(userName, hostName, port);
			session.setPassword(password);
			session.setConfig("StrictHostKeyChecking", "no");
			session.connect();
			
		} 
		catch (JSchException e) 
		{
			if (session != null)
			{
				session.disconnect();
				throw e;
			}
		}	
		return session;
	}
	
	public String runCommmand(String command, Session session) throws IOException, InterruptedException, JSchException
	{
		StringBuilder commandOutput = new StringBuilder();
		ChannelExec channel = null;
		try 
		{
			channel = (ChannelExec ) session.openChannel("exec");
			is = channel.getInputStream();
			channel.setCommand(command);
			channel.connect();

			byte[] buffer = new byte[1024];

			while (!channel.isClosed() || (is.available() > 0))
			{
				int i = is.read(buffer, 0, 1024);
				if (i < 0)
				{
					break;
				}
				commandOutput.append(new String(buffer, 0, i));
			}						
		} 
		catch (JSchException e) 
		{
			throw e;
		} 
		finally 
		{
			if (channel != null)
			{
				channel.disconnect();
				session.disconnect();
			}
		}
		
		return commandOutput.toString();
	}	
}
